package com.http.nio.core;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YL
 */
@Data
public class HttpParser {


    /**
     * <p>解析http请求体</p>
     *
     * @param buffers
     * @return
     */
    public static Request decodeReq(byte[] buffers) {
        Request request = new Request();

        if (buffers != null) {
            String resString = new String(buffers);
            System.out.println(resString);
            String[] headers = resString.trim().split("\r\n");
            if (headers.length > 0) {
                String faustine = headers[0];
                // 按空格分割字符串
                // 解析 method uri 协议版本
                String[] mainInfo = faustine.split("\\s+");
                request.setMethod(mainInfo[0]);
                try {
                    request.setUri(URLDecoder.decode(mainInfo[1], "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                request.setHttpVersion(mainInfo[2]);

                // 解析header
                Map<String, String> headersMap = new HashMap<>(headers.length);
                for (int i = 1; i < headers.length; i++) {
                    String entryStr = headers[i];
                    String[] entry = entryStr.trim().split(":");
                    headersMap.put(entry[0].trim(), entry[1].trim());
                }
                request.setHeaders(headersMap);

                // 解析参数
                String uri = request.getUri();
                Map<String, String> attribute = new HashMap<>();
                request.setPath(uri);
                if (StringUtils.isNotEmpty(uri)) {
                    int indexOfParam = uri.indexOf("?");
                    if (indexOfParam > 0) {

                        // 设置path
                        request.setPath(uri.substring(0, indexOfParam));
                        String queryString = uri.substring(indexOfParam + 1);
                        String[] paramEntrys = queryString.split("&");
                        for (String paramEntry : paramEntrys) {
                            String[] entry = paramEntry.split("=");
                            if (entry.length > 0) {
                                String key = entry[0];
                                String value = entry.length > 1 ? entry[1] : "";
                                attribute.put(key, value);
                            }
                        }
                    }
                }
                request.setAttribute(attribute);
            }
        }

        return request;
    }

    /**
     * <p>返回http响应字节流</p>
     *
     * @param response
     * @return
     */
    public static byte[] encodeResHeader(Response response) {
        StringBuilder resBuild = new StringBuilder();
        resBuild.append(response.getProtocol()).append(" ").append(response.getCode()).append(" ").append(response.getMsg());
        resBuild.append("\r\n");

        Map<String, String> headers = response.getHeaders();
        headers.forEach((key, value) -> {
            resBuild.append(key);
            resBuild.append(": ");
            resBuild.append(value);
            resBuild.append("\r\n");
        });
        resBuild.append("\r\n");

        String resString = resBuild.toString();
        return resString.getBytes(StandardCharsets.UTF_8);
    }

}
